package com.lizy.function
import org.apache.commons.codec.digest.DigestUtils;


class TokenAuth {
    /**
     * token鉴权
     * 通过开平key获取加密pk ——> mysql+tair
     * request入参调用getTokenStringAb方法获取入参排序字符串 a
     * a + pk 通过md5加密对比是否与token值相同
     *  why： 这个函数的作用还是不清楚 TODO ？？？
     */
    def process() {
        // 1. 将请求参数使用URLEncoder.encode进行编码获取字符串
        def queryStringEncode = getTokenStringAb(request);
        // 2. 将请求参数不经过编码获取字符串
        def queryString = getTokenString(request);
        // 3. 计算两种字符串饿md5是否一样
        def md5StrEncode =  DigestUtils.md5Hex(queryStringEncode+key)
        def md5Str = DigestUtils.md5Hex(queryString+key)
        if(token != md5Str && token != md5StrEncode){
            return false;
        }
        return true
    }

    public static def getTokenStringAb(Map<String, String> requestData) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> map = new TreeMap<>();
        for (Map.Entry<String, String> entry : requestData.entrySet()) {
            if ("token".equals(entry.getKey()) || null == entry.getValue()) {
                continue;
            }

            map.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            //获取Value
            sb.append(URLEncoder.encode(iterator.next().getValue(),"utf8"));
            sb.append(";");
        }
        return sb.toString();
    }

    public static def getTokenString(Map<String, String> requestData) {
        StringBuilder sb = new StringBuilder();
        Map<String, String> map = new TreeMap<>();
        for (Map.Entry<String, String> entry : requestData.entrySet()) {
            if ("token".equals(entry.getKey()) || null == entry.getValue()) {
                continue;
            }
            map.put(entry.getKey(), String.valueOf(entry.getValue()));
        }
        Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()) {
            //获取Value
            sb.append(iterator.next().getValue());
            sb.append(";");
        }
        return sb.toString();
    }

    static void main(String[] args) {
        println(new TokenAuth().process())
    }

    def key = """aaaaaaa"""
    def request = ["uid":"3fb423ec563046358868fea6c6d08cbe","modelName":"云产调用测试","appId":"208","tenantId":"820","key":"aaaaaaaaaaaaaaaa","timestamp":"1705044775"]
    def token = """ba7a067e07d6f8229c11efea2f5bcfda"""
}
